import { dev, manifest } from "@/env.js"
import { readPrompt, readPromptFile, resolvePromptReplaces } from "@/prompts/resolve.js"
import { defineTool } from "@/utils.js"
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
import { globSync } from "node:fs"
import { basename, resolve } from "node:path"

const promptsPrefix = "prompts://primaluce"

/**
 * 将所有资源 Markdown 文件注册为 MCP 资源。
 * 每个文件都会根据其语言自动应用默认替换（language、commitFile、prompts）。
 */
export function registerPromptResources(server: McpServer) {
  const resourcesDir = dev
    ? resolve(import.meta.dirname, "..", "..", "docs", "resources")
    : resolve("node_modules", manifest.name, "docs", "resources")
  const mdFiles = globSync("**/*.md", { cwd: resourcesDir })

  for (const file of mdFiles) {
    if (basename(file).toLowerCase() === "readme.md") continue
    const uri = `prompts://primaluce/${file.replace(/\.md$/, "")}`
    server.registerResource(file, uri, { title: `Resource: ${file}` }, (uri, _extra) => {
      // 确定语言：如果文件在语言子目录中，则使用子目录名称，否则为中文
      const parts = file.split("/")
      const language = parts.length > 1 && parts[0] !== "zh" ? parts[0] : "zh"
      const prompts = language === "zh" ? promptsPrefix : `${promptsPrefix}/${language}`
      const replaces = { language, commitFile: ".commit.md", prompts }

      const noExt = file.replace(/\.md$/, "")
      const name = parts.length > 1 ? parts.slice(1).join("/") : noExt
      const text = readPrompt(name, { language, replaces })
      return { contents: [{ uri: uri.toString(), mimeType: "text/markdown", text }] }
    })
  }
}

/**
 * 将所有工具 Markdown 文件注册为 MCP 工具。
 * 每个工具返回对应文件的内容，支持语言回退。
 */
export function registerTools(server: McpServer) {
  const toolsDir = dev
    ? resolve(import.meta.dirname, "..", "..", "docs", "tools")
    : resolve("node_modules", manifest.name, "docs", "tools")
  const mdFiles = globSync("**/*.md", { cwd: toolsDir })

  for (const file of mdFiles) {
    if (basename(file).toLowerCase() === "readme.md") continue
    // 工具名称基于文件名（不含扩展名和语言前缀）
    const parts = file.split("/")
    const language = parts.length > 1 && parts[0] !== "zh" ? parts[0] : "zh"
    const name = parts.length > 1 ? parts.slice(1).join("/") : file
    const baseName = name.replace(/\.md$/, "").replace(/\//g, "_")
    const toolName = `guide_${baseName}`
    const description = `Guide: ${baseName}`

    const tool = defineTool({
      name: toolName,
      description,
      callback(_extra) {
        const prompts = language === "zh" ? promptsPrefix : `${promptsPrefix}/${language}`
        const replaces = { language, commitFile: ".commit.md", prompts }
        const raw = readPromptFile(toolsDir, language, name, "utf8")
        const text = resolvePromptReplaces(raw, replaces)
        return { content: [{ type: "text", text }] }
      },
    })
    server.registerTool(...tool)
  }
}
